# -*- coding:utf8 -*-
# !/usr/bin/env python
from scpy.logger import get_logger
import requests

import cq_templatedict
import cq_transdict
import cq_transformfunction

MAXTIME = 10
logger = get_logger(__file__)


def fix_bug(company_name):
    response = requests.get('http://120.26.93.104:7100/api/saic/source?companyName=%s' % company_name)
    # response = requests.get('http://10.51.1.48:7100/api/saic/source?companyName=%s' % company_name)
    data = json.loads(response.content)
    source_data = json.loads(data["source"])

    # data['date']='2016-01-14'
    # print source_data['date']
    # 修改data 中的data 字段然后post (重要不要修改其他字段，同一条提交两次会修改上一次的内容)
    # print json.dumps(source_data, ensure_ascii=False, indent=4)
    # print json.dumps(json.loads(data["data"]), ensure_ascii=False, indent=4)

    test_dict = {
        'IcPublic': source_data['json'],
        'allAnnualReports': source_data['yearList'],
    }

    # 载入输出结果的模板字典
    atemplatedict_class = cq_templatedict.TemplateDict()
    template_dict = atemplatedict_class.returnTesttemplateDict()
    # print template_dict

    # 载入key转化字典
    aTransDict_class = cq_transdict.TransDict()
    keyTrans_dict = aTransDict_class.returnTesttransDict()
    # print keyTrans_dict

    # 载入转方法
    formfunction_class = cq_transformfunction.TransDictClass()
    fixed_data = formfunction_class.formatDicts(test_dict, template_dict, keyTrans_dict)

    data["data"] = json.dumps(fixed_data)

    # print json.dumps(data, ensure_ascii=False, indent=4)
    print json.dumps(fixed_data, ensure_ascii=False, indent=4)

    res = requests.post('http://120.26.93.104:7100/api/saic/source', data=json.dumps(data))
    # res = requests.post('http://10.51.1.48:7100/api/saic/source', data=json.dumps(data))
    print res.content


if __name__ == "__main__":

    import pymongo
    import json
    # pymongo.MongoClient('192.168.31.121', 27017)
    clientServer = pymongo.MongoClient('192.168.31.114', 27017)
    # clientServer = pymongo.MongoClient('10.132.23.104', 27017)
    db = clientServer.organization
    collectionServer = db.companyNameStrict
    # reg_no_s = collectionServer.find({'province': 'cq'})
    reg_no_s = collectionServer.find({'companyName': '重庆渝宁化肥有限公司'}).batch_size(30)
    for reg in reg_no_s:
        print '#' * 10
        print reg
        print '#' * 10
        company_name = reg['companyName']
        try:
            fix_bug(company_name)
        except Exception, e:
            import traceback

            traceback.print_exc()
            continue
            # print reg
            # import pdb
            # pdb.set_trace()
